<?php
/**
 * @author      :   ThuyNT
 * @modified    :   nhuantp@fpt.net
 * @name        :   AdminController
 * @version     :   20120326
 * @copyright   :   My company
 * @todo        :   controller default
 */
class Clbtoiyeu_AdminController extends Zend_Controller_Action
{
    /**
     * Category Config
     */
    private $categoryConfig = null;
    /**
     * Init controller
     */
    public function init()
    {
        //Get session
        $session    = Zend_Registry::get('session');

        //Get action name
        $actionName = $this->getRequest()->getActionName();

        //Array action not require login
        $arrActionNotRL = array('login');

        if ( (!isset($session->admin->user->id) || $session->admin->user->id<=0) && !in_array($actionName, $arrActionNotRL) )
        {
            $this->_redirect(BASE_URL_CLUB.'/admin/login');
        }//end if

        //Define user admin
        $userAdmin  = null;
        $userAdmin->id      = '-1';
        $userAdmin->email   = '';

        //Get global config
        $configuration  = Fpt_Global::getApplicationIni();
        if ( isset($configuration['club']['category']) )
        {
            $this->categoryConfig = $configuration['club']['category'];
        }
        else
        {
            $this->categoryConfig = array('none'=>0, 'listteam'=>1, 'eurohistory'=>2);
        }//end if

        //Assign to view
        $this->view->assign('categoryConfig', $this->categoryConfig);
        $this->view->assign('userAdmin', (isset($session->admin->user)?$session->admin->user:$userAdmin));

        //Add css header
        $this->view->headLink()->appendStylesheet(CSS_URL_CLUB . '/admin/admin.css', 'screen');
        $this->_helper->layout->setLayout('layout_admin');
    }

    /**
     * Login action
     */
    public function loginAction()
    {
        //Get session
        $session    = Zend_Registry::get('session');
        if ( isset($session->admin->user->id) && $session->admin->user->id>0 )
        {
            //Redirect
            $this->_redirect(BASE_URL_CLUB.'/admin');
        }//end if

        $error  = 0;
        if ( $this->getRequest()->isPost() )
        {
            //Get global config
            $configuration  = Fpt_Global::getApplicationIni();

            //Get param
            $arrParam   = $this->getRequest()->getParams();
            if ( empty($arrParam['txtEmail']) || $arrParam['txtEmail']!=$configuration['club']['admin']['user']['email'] || empty($arrParam['txtPass']) || md5($arrParam['txtPass'])!=md5($configuration['club']['admin']['user']['pass']) )
            {
                $error  = 1;
            }
            else
            {
                //Define user admin
                $userAdmin  = null;
                $userAdmin->id      = $configuration['club']['admin']['user']['id'];
                $userAdmin->email   = $configuration['club']['admin']['user']['email'];
                //Set session
                $session->admin->user   = $userAdmin;

                //Set session for fckinser
                $_SESSION['adminclbtoiyeu'] = 1;

                //Redirect
                $this->_redirect(BASE_URL_CLUB.'/admin');
            }//end if
        }//end if

        //Assign to view
        $this->view->assign('error', $error);

        //Head title
        $this->view->headTitle('CLB Tôi Yêu - Đăng Nhập Hệ Thống Quản Trị');
    }

    /**
     * Logout action
     */
    public function logoutAction()
    {
        //Get session
        $session    = Zend_Registry::get('session');
        unset($session->admin->user);

        //Unset session for fckinser
        unset($_SESSION['adminclbtoiyeu']);

        //Redirect
        $this->_redirect(BASE_URL_CLUB.'/admin/login');
    }

    /**
     * Index action
     */
    public function indexAction()
    {
        //Get ClubFavorite instance
        $CFInstance     = ClubFavorite::getInstance();
        //get param
        $req	= $this->getRequest();
        $para	= $req->getPost();
        if(!isset($para['categoryid']))
        {
            $para['categoryid'] = 3;
            $cateid = 3;
        }
        //Set limit, offset, num_link
        $limit  = 10;
        $curentPage     = $this->getRequest()->getParam('page');
        $cateid         = $this->getRequest()->getParam('cateid', $para['categoryid']);
        $status         = $this->getRequest()->getParam('status', 0);
        $para['categoryid'] = $cateid;
        if(!empty($status))
        {
            $para['status'] = $status;
        }
        $curentPage     = (is_numeric($curentPage) && $curentPage>0)?$curentPage:1;
        $offset         = ($curentPage-1)*$limit;
        $offset         = ($offset>=0)?$offset:0;
        $num_links      = 10;
        //get list hot new
        $listHotID = $CFInstance->getListHotNews();
        if(sizeof($listHotID) > 0)
        {
            $arrHotID = array();
            foreach ($listHotID as $k => $v)
            {
                $arrHotID[] = $v['articleid'];
            }
        }
        //get list article
        $arrData    = $CFInstance->getArticlesInfo($para,$limit,$offset);

        //List user
        $listUser   = array();
        if ( !empty($arrData['rows']) && is_array($arrData['rows']) )
        {
            foreach ( $arrData['rows'] as $row )
            {
                if ( $row['userid']>1000000000 && !in_array($row['userid'], $listUser) )
                {
                    $listUser[] = $row['userid'];
                }//end if
            }//end foreach
        }//end if

        //Get info
        $listUserInfo   = array();
        if ( !empty($listUser) && is_array($listUser) )
        {
            //Init Oauth
            $oauthDirect    = Fpt_Global::getDirectOauth();
            foreach ( $listUser as $userId )
            {
                //Get user info
                $userInfo   = Zend_Json::decode($oauthDirect->execUserByMethodGetUserID(array('userid'=>Zend_Json::encode(array($userId)), 'viewid'=>$userId)));
                $listUserInfo[$userId]  = (isset($userInfo['response']['result'][$userId]) && is_array($userInfo['response']['result'][$userId]))?$userInfo['response']['result'][$userId]:array('fullname'=>'', 'email'=>'');
            }//end foreach
        }//end if

        //Set profile admin
        $listUserInfo[0]    = array('fullname'=>'Admin post', 'email'=>'');

        $total = $arrData['total'];
        //Get paging
        $pagingHTML = '';
        if ( $total > $limit )
        {
            $arrOption  = array(
                    'base_url'      => BASE_URL_CLUB.'/admin/index/cateid/'.$cateid.'/status/'.$status,
                    'total_rows'    => $total,
                    'per_page'      => $limit,
                    'num_links'     => $num_links,
                    'cur_page'      => $curentPage
            );
            $objPaging  = new Util_Pagination($arrOption);
            $pagingHTML = $objPaging->create_links();
        }//end if

        //Assign view
        $this->view->assign('pagingHTML', $pagingHTML);
        $this->view->assign('listHotID', $arrHotID);
        $this->view->assign("arrSearch",$para);
        $this->view->assign("arrData",$arrData['rows']);
        $this->view->assign("total",$total);
        $this->view->assign("CURR_URL",'Quản lý tin >> Danh sách');
        $this->view->assign("SET_INDEX",'news');
        $this->view->assign("listUserInfo", $listUserInfo);

        //Head title
        $this->view->headTitle('Quản lý CLB Tôi Yêu - Trang Chủ');
    }
    public function detailAction()
    {
        $id = $this->_request->getParam('id','');
        if(!empty ($id))
        {
            //Get ClubFavorite instance
            $CFInstance     = ClubFavorite::getInstance();
            //delete articles
            $arrData = $CFInstance->getArticleDetail($id);
        }
        //Assign view
        $this->view->assign("CURR_URL",'Quản lý tin >> Chi tiết');
        $this->view->assign("SET_INDEX",'news');
        $this->view->assign('arrData',$arrData);
        $this->view->headTitle('Quản lý CLB Tôi Yêu - Chi tiết');
    }
    /*
     * delete acrticle
    */
    public function deletearticleAction()
    {
        $id = $this->_request->getParam('id','');
        if(!empty($id))
        {
            //Get ClubFavorite instance
            $CFInstance     = ClubFavorite::getInstance();
            $articleDetail  = $CFInstance->getArticleDetail($id);
            if ( isset($articleDetail['articleid']) && is_numeric($articleDetail['articleid']) && $articleDetail['articleid']>0 && $articleDetail['status']!=0 )
            {
                //Set params
                $params = array(
                        'articleid'     => $articleDetail['articleid'],
                        'status'        => 0,
                        'status_old'    => $articleDetail['status'],
                        'categoryid'    => $articleDetail['categoryid'],
                        'userid'        => $articleDetail['userid']
                );

                //delete articles
                $result = $CFInstance->updateArticleStatus($params);

                //Check success
                if($result == 1)
                {
                    if ( isset($articleDetail['image']) && !empty($articleDetail['image']) )
                    {
                        unlink(dirname(UPLOAD_PATH_CLUB).$articleDetail['image']);
                    }//end if

                    //Redirect List Article
                    $this->_redirect(BASE_URL_CLUB.'/admin/');
                }
                else
                {
                    die("Có lỗi xảy ra, vui lòng thực hiện lại sau.");
                }//end if
            }//end if
        }

        $this->_redirect(BASE_URL_CLUB.'/admin/');
    }
    /*
     * update status for article
    */
    public function updatestatusAction()
    {
        $id = $this->_request->getParam('id','');
        $status = $this->_request->getParam('status','');
        if(isset($status))
        {
            if($status == 1)
            {
                $tamp = 2; //InActive
            }
            else
            {
                $tamp = 1; // Active
            }
        }
        if(!empty($id))
        {
            //Get ClubFavorite instance
            $CFInstance     = ClubFavorite::getInstance();
            $articleDetail  = $CFInstance->getArticleDetail($id);
            if ( isset($articleDetail['articleid']) && is_numeric($articleDetail['articleid']) && $articleDetail['articleid']>0 && $articleDetail['status']!=0 && $articleDetail['status']!=$tamp )
            {
                //Set params
                $params = array(
                        'articleid'     => $articleDetail['articleid'],
                        'status'        => $tamp,
                        'status_old'    => $articleDetail['status'],
                        'categoryid'    => $articleDetail['categoryid'],
                        'userid'        => $articleDetail['userid']
                );
                //Update articles status
                $result = $CFInstance->updateArticleStatus($params);
                if($result == 1)
                {
                    //Redirect List Article
                    $this->_redirect(BASE_URL_CLUB.'/admin/');
                }
                else
                {
                    die("Có lỗi xảy ra, vui lòng thực hiện lại sau.");
                }//end if
            }
        }

        //Redirect List Article
        $this->_redirect(BASE_URL_CLUB.'/admin/');
    }

    /**
     * set hot for article
     */
    public function sethotAction()
    {
        $id = $this->_request->getParam('id','');

        if(!empty($id))
        {
            //Get ClubFavorite instance
            $CFInstance     = ClubFavorite::getInstance();
            $articleDetail  = $CFInstance->getArticleDetail($id);

            //Insert articles hot
            $result = 0;
            if ( isset($articleDetail['articleid']) && is_numeric($articleDetail['articleid']) && $articleDetail['articleid']>0 && $articleDetail['status']==1 && $articleDetail['categoryid']!=$this->categoryConfig['eurohistory'] )
            {
                //get list hot new
                $listHotID = $CFInstance->getListHotNews();
                $arrHotID = array();
                if(sizeof($listHotID) > 0)
                {
                    foreach ($listHotID as $k => $v)
                    {
                        $arrHotID[] = $v['articleid'];
                    }
                }

                if ( !in_array($articleDetail['articleid'], $arrHotID) )
                {
                    $arrParams = array(
                            'articleid'     => $articleDetail['articleid'],
                            'userpost'      => $articleDetail['userid'],
                            'display_order' => 1,
                            'categoryid'    => $articleDetail['categoryid']
                    );
                    $result = $CFInstance->insertHotNews($arrParams);
                }//end if
            }//end if
            if($result > 0)
            {
                //Redirect List Article
                $this->_redirect(BASE_URL_CLUB.'/admin/');
            }
            else
            {
                die("Có lỗi xảy ra, vui lòng thực hiện lại sau.");
            }//end if
        }
        else
        {
            //Redirect List Article
            $this->_redirect(BASE_URL_CLUB.'/admin/');
        }//end if
    }

    /**
     * Unset hot for article
     */
    public function unsetsethotAction()
    {
        $id = $this->_request->getParam('id','');

        if ( !empty($id) )
        {
            //Get ClubFavorite instance
            $CFInstance     = ClubFavorite::getInstance();
            $articleDetail  = $CFInstance->getArticleDetail($id);

            //Insert articles hot
            $result = 0;
            if ( isset($articleDetail['articleid']) && is_numeric($articleDetail['articleid']) && $articleDetail['articleid']>0 && $articleDetail['status']==1 && $articleDetail['categoryid']!=$this->categoryConfig['eurohistory'] )
            {
                //get list hot new
                $listHotID = $CFInstance->getListHotNews();
                $arrHotID = array();
                if ( sizeof($listHotID) > 0 )
                {
                    foreach ( $listHotID as $k=>$v )
                    {
                        $arrHotID[] = $v['articleid'];
                    }//end foreach
                }//end if

                if ( in_array($articleDetail['articleid'], $arrHotID) )
                {
                    $arrParams = array(
                            'articleid'     => $articleDetail['articleid'],
                            'categoryid'    => $articleDetail['categoryid']
                    );
                    $result = $CFInstance->deleteHotNews($arrParams);
                }//end if
            }//end if

            if ( $result > 0 )
            {
                //Redirect List Article
                $this->_redirect(BASE_URL_CLUB.'/admin/');
            }
            else
            {
                die("Có lỗi xảy ra, vui lòng thực hiện lại sau.");
            }//end if
        }
        else
        {
            //Redirect List Article
            $this->_redirect(BASE_URL_CLUB.'/admin/');
        }//end if
    }

    /**
     * Post action
     */
    public function postAction()
    {
        //Set error
        $error  = 0;

        if ( $this->_request->isPost() )
        {
            //Get ClubFavorite instance
            $CFInstance = ClubFavorite::getInstance();

            //Get param
            $params = $this->getRequest()->getParams();

            //Upload file image
            $uploaded_file  = new Zend_File_Transfer_Adapter_Http();
            $uploaded_file->addValidator('FilesSize', false, 2000000);
            $uploaded_file->addValidator('Extension', false, array('jpg', 'gif', 'png'));
            //Upload file
            $thumb      = $CFInstance->uploadFile(0, $_FILES['txtfile']['name'], $uploaded_file, dirname(UPLOAD_PATH_CLUB), UPLOAD_PATH_CLUB.'/');

            //Set param insert
            $paramInsert    = array(
                    'userid'        => 0,
                    'user_type'     => 2,
                    'categoryid'    => $params['categoryid'],
                    'title'         => strip_tags($params['txtTitle']),
                    'content'       => $params['ck_content'],
                    'status'        => $params['status'],
                    'image'         => !empty($thumb['thumb'])?$thumb['thumb']:'',
                    'url'           => '',
                    'home'          => '',
                    'award'         => '',
                    'info'          => '',
                    'coachman'      => ''
            );

            //Check post list team
            if ( $params['categoryid'] == $this->categoryConfig['listteam'] )
            {
                $paramInsert['home']        = strip_tags($params['txtHome']);
                $paramInsert['award']       = strip_tags($params['txtAward']);
                $paramInsert['info']        = strip_tags($params['txtInfo']);
                $paramInsert['coachman']    = strip_tags($params['txtCoach']);
            }//end if

            //Insert
            $result  = $CFInstance->insertArticle($paramInsert);

            //Redirect detail page
            if ( $result > 0 )
            {
                $this->_redirect(BASE_URL_CLUB.'/admin');
            }
            else
            {
                //Error
                $error  = 1;
            }//end if
        }//end if

        //Assign to view
        $this->view->assign('error', $error);

        //Head script
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/post-article.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/ckeditor/ckeditor.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/ckeditor/ckeditor_module.js', 'text/javascript');
        $this->view->assign("CURR_URL",'Post bài');
        $this->view->assign("SET_INDEX",'post');
        //Head title
        $this->view->headTitle('CLB Tôi Yêu - Thêm Bài Dự Thi');
    }
    /**
     * Update action
     */
    public function updateAction()
    {
        //Set error
        $error  = 0;
        //Get ClubFavorite instance
        $CFInstance     = ClubFavorite::getInstance();
        //get param
        $req	= $this->getRequest();
        $id = $this->_request->getParam('id','');
        $arrData = array();
        if(!empty ($id))
        {
            //Get ClubFavorite instance
            $CFInstance     = ClubFavorite::getInstance();
            //delete articles
            $arrData = $CFInstance->getArticleDetail($id);
        }
        if($req->isPost())
        {
            //Get param
            $params = $req->getPost();

            if ( !isset($params['txtid']) || !is_numeric($params['txtid']) || $params['txtid']<=0 )
            {
                $this->_redirect(BASE_URL_CLUB.'/admin');
            }//end if

            //Get ClubFavorite instance
            $CFInstance = ClubFavorite::getInstance();

            //Get detail
            if ( !empty($arrData) && is_array($arrData) )
            {
                $articleDetail  = $arrData;
            }
            else
            {
                $articleDetail  = $CFInstance->getArticleDetail($params['txtid']);
            }//end if

            if ( !isset($articleDetail['articleid']) || !is_numeric($articleDetail['articleid']) || $articleDetail['articleid']<=0 || $articleDetail['status']==0 )
            {
                $this->_redirect(BASE_URL_CLUB.'/admin');
            }//end if

            //Upload file image
            $uploaded_file  = new Zend_File_Transfer_Adapter_Http();
            $uploaded_file->addValidator('FilesSize', false, 2000000);
            $uploaded_file->addValidator('Extension', false, array('jpg', 'gif', 'png'));
            if ( isset($_FILES['txtfile']['name']) && !empty($_FILES['txtfile']['name']) )
            {
                //Upload file
                $thumb      = $CFInstance->uploadFile($params['txtid'], $_FILES['txtfile']['name'], $uploaded_file, dirname(UPLOAD_PATH_CLUB), UPLOAD_PATH_CLUB.'/');
            }
            else
            {
                $image = $params['image'];
            }//end if
            
            //Set param insert
            $paramsUpdate    = array(
                    'articleid'     => $params['txtid'],
                    'userid'        => $articleDetail['userid'],
                    'user_type'     => $articleDetail['user_type'],
                    'title'         => strip_tags($params['txtTitle']),
                    'content'       => $params['ck_content'],
                    'image'         => !empty($thumb['thumb'])?$thumb['thumb']:$image,
                    'url'           => '',
                    'status'        => $params['status'],
                    'status_old'    => $articleDetail['status'],
                    'categoryid'    => $articleDetail['categoryid'],
                    'home'          => '',
                    'award'         => '',
                    'info'          => '',
                    'coachman'      => ''
            );

            //Check post list team
            if ( $articleDetail['categoryid'] == $this->categoryConfig['listteam'] )
            {
                $paramsUpdate['home']        = strip_tags($params['txtHome']);
                $paramsUpdate['award']       = strip_tags($params['txtAward']);
                $paramsUpdate['info']        = strip_tags($params['txtInfo']);
                $paramsUpdate['coachman']    = strip_tags($params['txtCoach']);
            }//end if

            //Insert
            $articleId  = $CFInstance->updateArticle($paramsUpdate);

            //Redirect detail page
            if ( $articleId > 0 )
            {
                $this->_redirect(BASE_URL_CLUB.'/admin');
            }
            else
            {
                //Error
                $error  = 1;
            }//end if

            //Assign to view
            $this->view->assign('error', $error);
        }
        //Head script
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/post-article.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/ckeditor/ckeditor.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/ckeditor/ckeditor_module.js', 'text/javascript');

        //Assign view
        $this->view->assign('arrData',$arrData);
        $this->view->assign("CURR_URL",'Quản lý tin >> Cập nhật');
        $this->view->assign("SET_INDEX",'news');
        $this->view->headTitle('Quản lý CLB Tôi Yêu - Cập Nhật Bài Dự Thi');
    }
    /*
     * get list comment action
    */
    public function listcommentAction()
    {
        //Get ClubFavorite instance
        $CFInstance     = ClubFavorite::getInstance();

        //Get param
        $params = $this->getRequest()->getParams();

        //Check param
        $params['type'] = isset($params['type'])?$params['type']:2;
        if ( isset($params['RDC'][0]) )
        {
            $params['type'] = $params['RDC'][0];
        }//end if

        //Set limit, offset, num_link
        $limit  = 10;
        $curentPage     = isset($params['page'])?$params['page']:1;
        $articleid      = (isset($params['id']) && is_numeric($params['id']) && $params['id']>0)?$params['id']:0;
        $curentPage     = (is_numeric($curentPage) && $curentPage>0)?$curentPage:1;
        $offset         = ($curentPage-1)*$limit;
        $offset         = ($offset>=0)?$offset:0;
        $num_links      = 10;
        $total = 0;
        $arrData    = array('list'=>null, 'total'=>0);
        if ( $articleid>0 && $params['type']==2 )
        {
            //Get list article
            $arrData    = $CFInstance->getListComment($articleid, $limit, $offset);
        }
        else
        {
            $articleid  = 0;
            //Get list article
            $arrData    = $CFInstance->getListCommentNew($limit, $offset);
        }//end if

        //Check data
        if ( !empty($arrData['list']) )
        {
            $total = $arrData['total'];

            //Get paging
            $pagingHTML = '';
            if ( $total > $limit )
            {
                $arrOption  = array(
                        'total_rows'    => $total,
                        'per_page'      => $limit,
                        'num_links'     => $num_links,
                        'cur_page'      => $curentPage
                );
                if ( $articleid > 0 )
                {
                    $arrOption['base_url']  = BASE_URL_CLUB.'/admin/listcomment/type/2/id/'.$articleid;
                }
                else
                {
                    $arrOption['base_url']  = BASE_URL_CLUB.'/admin/listcomment/type/1';
                }//end if
                $objPaging  = new Util_Pagination($arrOption);
                $pagingHTML = $objPaging->create_links();
            }//end if
            $this->view->assign('pagingHTML', $pagingHTML);
        }//end if

        //Assign view
        $this->view->assign("type",$params['type']);
        $this->view->assign("articleid",$articleid);
        $this->view->assign("arrData",!empty($arrData['list'])?$arrData['list']:'');
        $this->view->assign("total",$total);
        $this->view->assign("CURR_URL",'Quản lý bình luận');
        $this->view->assign("SET_INDEX",'comment');
        $this->view->headTitle('Quản lý CLB Tôi Yêu - Quản Lý Bình Luận');
    }
    /*
     * delete comment
    */
    public function deletecommentAction()
    {
        //Get param
        $id         = $this->_request->getParam('commentid','');
        $articleid  = $this->_request->getParam('articleid','');
        $type       = $this->_request->getParam('type',1);
        if ( !empty($id) && is_numeric($id) && $id>0 )
        {
            //Get ClubFavorite instance
            $CFInstance     = ClubFavorite::getInstance();
            //delete articles
            $result = $CFInstance->deleteComment($id,$articleid);
            if ( $result )
            {
                if ( $type == 1 )
                {
                    //Redirect List Comment
                    $this->_redirect(BASE_URL_CLUB.'/admin/listcomment/type/1');
                }
                else
                {
                    //Redirect List Comment
                    $this->_redirect(BASE_URL_CLUB.'/admin/listcomment/type/2/id/'.$articleid);
                }//end if
            }
            else
            {
                die("Có lỗi xảy ra, vui lòng thực hiện lại sau.");
            }//end if
        }//end if

        //Redirect List Comment
        $this->_redirect(BASE_URL_CLUB.'/admin/listcomment/type/1');
    }
}
?>